package controller

import (
	"jtvss/api/operation/model"
	"jtvss/api/operation/service"
	"jtvss/middleware"
	"jtvss/pkg/ctx"
	"jtvss/pkg/orm"
	"jtvss/util"

	"github.com/gin-gonic/gin"
)

// Fleet
type Fleet struct {
}

// ListHandler 列表
func (o *Fleet) ListHandler(c *gin.Context) {
	tok := middleware.UserToken(c)
	var data []model.Organization
	toatl, _ := orm.DbFindBy(&data, "GUID = ?", tok.OrganizeGUID)
	ctx.JSONWriteTotal(toatl, data, c)
}

// TreeHandler 列表
func (o *Fleet) TreeHandler(c *gin.Context) {
	data := service.OrganizeTree(middleware.UserToken(c).OrganizeGUID, nil)
	ctx.JSONWriteData(data, c)
}

// GetHandler 详细
func (o *Fleet) GetHandler(c *gin.Context) {
	util.QueryByID(&model.Organization{}, c)
}

// AddHandler 新增
func (o *Fleet) AddHandler(c *gin.Context) {
	var p model.Organization
	//获取参数
	if err := c.ShouldBind(&p.OrganizationOpt); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	// 获取组织信息, 从数据库
	p.GUID = middleware.UserToken(c).OrganizeGUID
	if err := orm.DbCreate(&p); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	ctx.JSONWriteData(nil, c)
}

// UpdateHandler 修改
func (o *Fleet) UpdateHandler(c *gin.Context) {
	var p model.Organization
	//获取参数
	if err := c.ShouldBind(&p.OrganizationOpt); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	if err := orm.DbUpdateModel(&p); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	ctx.JSONWriteData(nil, c)
}

// DeleteHandler 删除
func (o *Fleet) DeleteHandler(c *gin.Context) {
	util.Deletes(&model.Organization{}, c)
}

func (o Fleet) Routers(r *gin.RouterGroup) {
	r.GET("/list", o.ListHandler)
	r.GET("/tree", o.TreeHandler)
	r.GET("/:id", o.GetHandler)
	r.POST("", o.AddHandler)
	r.PUT("", o.UpdateHandler)
	r.DELETE("/:id", o.DeleteHandler)
}
